/*
 * 完整的客户头记录
 */
Ext.onReady(function(){
	Ext.lib.Ajax.defaultPostHeader += '; charset=utf-8';//处理ie提交中文乱码问题
    var fm = Ext.form;
	var sm = new Ext.grid.CheckboxSelectionModel({handleMouseDown: Ext.emptyFn});
    var cm = new Ext.grid.ColumnModel([
		sm,{
			header:'编号',
			dataIndex:'customerId',
			width:40
		},{
			header: "客户名称",
			dataIndex: 'customerName',
			editor: new fm.TextField({
				allowBlank: false
			})
        },{
			header:'客户编码',
			dataIndex:'customerNumber',
			width:120,
			align:'center',			
			editor: new fm.NumberField({
				allowBlank: false
			})
		},{
			header:'组织名称',
			dataIndex:'accountName',
			width:120,
			align:'center',			
			editor: new fm.TextField({
				allowBlank: false
			})
		}
    ]);
    cm.defaultSortable = true;

    var SaleArea = Ext.data.Record.create([
           {name: 'customerId', type: 'int'},
           {name: 'customerName', type: 'string'},
		   {name: 'customerNumber',type:'int'},	
		   {name: 'accountName',type:'string'}	
      ]);

	var store = new Ext.data.JsonStore({
		url:'../'+WebServiceUrl,
		baseParams:{trancode:'11160'},
		totalProperty:'totalProperty',
		root:'root',
		fields:SaleArea,
		pruneModifiedRecords:true
		//sortInfo: {field: "regionId", direction: "ASC"} //设置默认排序规则, EditorGridPanel在新增加一行却未保存时如果点击header排序会出现'行142字符6983,modified为空或不是对象'
	});

	//表单窗体
	var memberAddWindow;

    var grid = new Ext.grid.EditorGridPanel({
        store: store,
        cm: cm,
        renderTo: 'customer_grid',
        resizeable:true,
        height : Ext.get("customer_grid").getHeight(),
		bodyStyle : 'width:100%',
        title:'客户头信息',
        clicksToEdit:1,
		sm:sm,
		iconCls:'icon-grid',
		loadMask: {msg:'正在加载数据，请稍候。。。'},
		stripeRows:true,
		tbar:[
		{// 添加按钮
			text:'添加',
			iconCls:'add',
			handler:function(){
				var m = new SaleArea({
					customerName:'名称',
					customerNumber:'11',
					accountName:'名称'
				});
				grid.stopEditing();
				store.insert(0, m);
				grid.startEditing(0, 2);
				store.getAt(0).dirty=true; // 设置该行记录为脏数据(默认为非脏数据),否则在保存时将无法判断该行是否已修改
			}
		},'-',{
			id:'newWindowButton',
			text:'新面板中添加',
			iconCls:'add',
			handler:function(){
			    showMemerAddWindow(); //显示表单所在窗体
			}
		},'-',{//删除按钮
			id:'btnDelete',
			text:'删除',
			iconCls:'remove',
			handler:function(){
				var sm = grid.getSelectionModel();
				var selected = sm.getSelections();
				var ids = [];
				for(var i=0;i<selected.length;i+=1){
					var member = selected[i].data;
					if(member.customerId) {
						ids.push(member.customerId); //如果有customerId属性,则表示该行数据是被修改过的,所以需要访问数据库进行删除
					}else{
						//如果没有customerId属性,则表示该行数据是新添加的未保存的数据,所以不需要访问数据库进行删除该行
						store.remove(store.getAt(i));
					}
				}
				if(ids.join('')=='') return;				
				Ext.Msg.confirm('信息','确定要删除所选项吗?',function(btn){
					if(btn=='yes'){
						//发送删除请求
						Ext.lib.Ajax.request(
							'POST',
							'../'+WebServiceUrl,{
								success:function(result){
									json = Ext.util.JSON.decode(result.responseText);
									if (json.success) {
										Ext.MessageBox.alert('操作成功',json.message);
									} else {
										Ext.MessageBox.alert('操作失败',json.message);
									}
									store.reload();
								}
							},
							'trancode=11164&id='+ids
						);
					}
				});
			}
		},'-',{//保存按钮
			text:'保存',
			iconCls:'save',
			handler:function(){
				var json = [];
				for(i=0,cnt=store.getCount();i<cnt;i+=1){
					var record = store.getAt(i);
					if(record.dirty) // 得到所有修改过的数据
						json.push(record.data);
				}
				if(json.length==0){
					Ext.Msg.alert('信息','没有对数据进行任何更改');
					return;
				}
				//发送保存请求
				Ext.lib.Ajax.request(
					'POST',
					'../'+WebServiceUrl,{
						success:function(result){							
							json = Ext.util.JSON.decode(result.responseText);
							if (json.success) {
								Ext.MessageBox.alert('操作成功',json.message);
							} else {
								Ext.MessageBox.alert('操作失败',json.message);
							}
							store.reload();							
						}
					},
					'trancode=11163&Customer='+encodeURIComponent(Ext.encode(json))
				);
			}
		},'-'],
	    bbar: new Ext.PagingToolbar({
	        pageSize: App.pageSize,
	        store: store,
	        displayInfo: true,
	        displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
	        emptyMsg: "没有记录"
	    })

    });
    store.load({params:{start:0,limit:App.pageSize}});	
	/**
	 * 以下是表单 __________________________________________________
	 * */
	//客户名称字段
	var noField = new Ext.form.TextField({
		fieldLabel:'客户名称',
		name:'customerName',
		allowBlank:false,
        anchor:'90%'
	});
	//客户编码字段
	var nameField = new Ext.form.NumberField({
		fieldLabel:'客户编码',
		name:'customerNumber',
		allowBlank:false,
        anchor:'90%'
	});
	//组织名称字段
	var regField = new Ext.form.TextField({
		fieldLabel:'组织名称',
		name:'accountName',
		allowBlank:false,
        anchor:'90%'
	});
	//表单对象
    var memberForm = new Ext.FormPanel({
        labelAlign: 'top',
        frame:true,
        title: '添加客户头信息',
        width: 300,
        url:'../'+WebServiceUrl+'?trancode=11162',        
        items: [noField,nameField,regField],
        buttons:[{
	        text:'提交',
	        handler:function(){
	        	if(memberForm.form.isValid())
		        	memberForm.form.submit({
		        		waitMsg:'保存中,请稍后...',
		        		success:function(form,action){
		        			if (action.result.success) {
								Ext.MessageBox.alert('操作成功',action.result.message);
								memberAddWindow.hide();
							} else {
								Ext.MessageBox.alert('操作失败',action.result.message);
							}
		        			store.reload();
		        		}
		        	});
	        }
	    },{
	    	text:'取消',
	    	handler:function(){
	    		memberForm.getForm().reset();
	    		memberAddWindow.hide();
	    	}
	    }]
    });    
    //窗体对象
    function showMemerAddWindow(){
	    if(!memberAddWindow){
			memberAddWindow = new Ext.Window({
			    el:'window_win',
			    layout:'fit',
			    width:300,
			    height:250,
			    closable:true,
			    closeAction:'hide',
		        plain:true,
			    items: [memberForm]
			});
	    }
		memberAddWindow.show(Ext.get('newWindowButton'));
    }
});
